from django.http import JsonResponse, HttpResponse
import json
from .models import *
from users.models import *
from datetime import datetime
from django.contrib.auth.decorators import login_required
from utils.json_schema import *
from utils.json_validate import json_validate
from notifications.signals import notify


# 创建订单
@login_required()
@json_validate(create_work_schema)
def create_work(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 订单类型 批量或自主 1为批量 2为自主
    type = req_data["type"]
    # 出版社名称
    name = req_data["name"]
    data_dict = {}
    work = Work()
    if "remark" in req_data.keys():
        work.remark = req_data["remark"]
        data_dict["remark"] = work.remark
    if type == 2:
        if "template" in req_data.keys():
            work.template = req_data["template"]
            data_dict["template"] = work.template
        else:
            data = {"success": False, "data": {"msg": "此出版社订单为自主模式，请将模板名称填入。"}}
            return JsonResponse(data)
    work.type = type
    data_dict["type"] = work.type
    work.name = name
    data_dict["name"] = work.name
    work.create_user = request.user.name
    work.create_date = datetime.now()
    work.save()
    data = {"success": True, "data": {"msg": "录入新订单成功！", "data": data_dict}}
    return JsonResponse(data)


# 录入书籍
@login_required()
@json_validate(create_books_schema)
def create_books(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    work_id = req_data["work_id"]
    contents = req_data["contents"]
    query_list = []
    data_list = []
    try:
        work = Work.objects.get(id=work_id)
    except Exception as e :
        data = {"success": False, "data": {"msg": "查询订单失败！"}}
        return JsonResponse(data)
    for content in contents:
        try:
            Books.objects.get(code=content["code"])
            data = {"success": False, "data": {"msg": "图书编号应为唯一不重复的字符串，请重新输入！"}}
            return JsonResponse(data)
        except Exception as e:
            data_dict = {}
            book = Books()
            book.code = content["code"]
            book.name = content["name"]
            book.work = work
            data_dict["code"] = content["code"]
            data_dict["name"] = content["name"]
            data_dict["work"] = book.work.name
            data_list.append(data_dict)
            query_list.append(book)
    Books.objects.bulk_create(query_list)
    data = {"success": True, "data": {"msg": "录入图书成功！", "data": data_list}}
    return JsonResponse(data)


# 创建任务（书）
@login_required()
# @json_validate(create_tasks_schema)
def create_tasks(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    query_list = []
    history_list = []
    data_list = []
    content_list = req_data["data"]
    for content in content_list:
        for stage_type in range(1, 3):
            data_dict = {}
            task = Task()
            # 根据code找到对应的图书并关联
            code = content["code"]
            try:
                book = Books.objects.get(code=code)
            except Exception as e:
                data = {"success": False, "data": {"msg": "查询图书错误或图书不存在，请重试！"}}
                return JsonResponse(data)
            # 获取stage
            try:
                stage = StageName.objects.get(id=1)
            except Exception as e:
                data = {"success": False, "data": {"msg": "任务创建出错请重新创建!"}}
                return JsonResponse(data)
            user = request.user
            task.code = book
            task.diedline = content["diedline"]
            task.stage_type = stage_type
            task.stage = stage
            task.state = 4
            task.next_stage = 2
            task.create_user = user.name
            task.save()
            query_list.append(task)
            # 创建历史数据
            history = History()
            history.book = book
            history.task = task
            history.stage = task.stage
            history.user = user
            history.start_time = datetime.now()
            history_list.append(history)
            data_dict["code"] = book.code
            data_dict["diedline"] = content["diedline"]
            data_dict["stage"] = stage.name
            data_dict["stage_type"] = stage_type
            data_dict["state"] = 4
            data_dict["next_stage"] = 2
            data_dict["create_user"] = user.name
            data_list.append(data_dict)
    # Task.objects.bulk_create(query_list)
    History.objects.bulk_create(history_list)
    data = {"success": True, "data": {"msg": "录入任务完成!", "data": data_list}}
    return JsonResponse(data)


# 查询未完成的订单
@login_required()
def get_undone_work(request):
    if request.method =='GET':
        # import pdb
        # pdb.set_trace()
        works = Work.objects.exclude(state=2)
        # data_list = serializers.serialize('json', work)
        data_list = []
        for work in works:
            data_dict = {}
            data_dict["name"] = work.name
            data_dict["type"] = work.type
            data_dict["state"] = work.state
            data_dict["create_user"] = work.create_user
            data_dict["create_date"] = work.create_date
            if work.remark:
                data_dict["remark"] = work.remark
            if work.template:
                data_dict["template"] = work.template
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)
    else:
        data = {"success": False, "data": {"msg": "请发送GET请求!"}}
        return JsonResponse(data)


# 查询任务
@login_required()
def get_task(request):
    query_list = []
    if request.method == 'POST':
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        tasks = Task.objects.all().order_by('code', 'id')
        query_list.append(tasks)
        # 按照出版社名称查询
        if "work_name" in req_data.keys():
            works = Work.objects.filter(name=req_data["work_name"])
            query_list.clear()
            for work in works:
                list1 = []
                books = work.bookOfWork.all()
                for book in books:
                    tasks = book.taskOfBook.all().order_by('-id')
                    for task in tasks:
                        list1.append(task)
                query_list.append(list1)
        # 按照任务编号查询
        if "code" in req_data.keys():
            list1 = []
            if len(query_list) > 0:
                for query in query_list:
                    task = query.filter(code=Books.objects.get(code=req_data["code"])).order_by('-id')
                    list1.append(task)
            else:
                task = Task.objects.filter(code=Books.objects.get(code=req_data["code"]))
                list1.append(task)
            query_list = list1
        # 按照任务当前状态查询 1等待分配 2进行中 3已完成
        if "state" in req_data.keys():
            list1 = []
            if len(query_list) > 0:
                for query in query_list:
                    task = query.filter(state=req_data["state"]).order_by('-id')
                    list1.append(task)
            else:
                task = tasks.filter(state=req_data["state"]).order_by('-id')
                list1.append(task)
            query_list = list1
        # 查询已逾期的任务
        if "diedline" in req_data.keys():
            list1 = []
            if len(query_list) > 0:
                for query in query_list:
                    task = query.filter(diedline__lt=datetime.now(), state__in=[1, 2, 4]).order_by('-id')
                    list1.append(task)
            else:
                task = tasks.filter(diedline__lt=datetime.now(), state__in=[1, 2, 4]).order_by('-id')
                list1.append(task)
            query_list = list1

        # 根据人员查任务
        if "username" in req_data.keys():
            user = Users.objects.get(name=req_data["username"])
            tasks = user.task.all()
            query_list.clear()
            query_list.append(tasks)
    if request.method == 'GET':
        tasks = Task.objects.all().order_by('code', '-id')
        query_list.append(tasks)
    data_list = []
    for tasks in query_list:
        for task in tasks:
            data_dict = {}
            data_dict["id"] = task.id
            data_dict["code"] = task.code.code
            data_dict["work"] = task.code.work.name
            data_dict["stage"] = task.stage.name
            data_dict["state"] = task.state
            data_dict["diedline"] = task.diedline
            data_dict["create_date"] = task.create_date
            data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 查询出待分配的任务
@login_required()
def get_undistribute_task(request):
    if request.method == 'GET':
        tasks = Task.objects.filter(state=1, stage__lt=5)
        data_list = []
        for task in tasks:
            data_dict = {}
            data_dict["id"] = task.id
            data_dict["code"] = task.code.code
            data_dict["work"] = task.code.work.name
            data_dict["stage"] = task.stage.name
            data_dict["state"] = task.state
            data_dict["diedline"] = task.diedline
            data_dict["create_date"] = task.create_date
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)


# 查询相对应阶段的涉及人员
@login_required()
def get_work_users(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    position = req_data["stage"]
    users = Users.objects.filter(position=position)
    data_list = []
    for user in users:
        data_dict = {}
        data_dict["id"] = user.id
        data_dict["name"] = user.name
        data_dict["position"] = user.position
        data_dict["task_counts"] = user.task.all().count()
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 分配任务
@login_required()
@json_validate(distribute_task_schema)
def distribute_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 需要分配的任务id列表
    task_list = req_data["task_list"]
    # 获取被分配任务的员工id
    user_id = req_data["user_id"]
    # 创建一个空列表 用于存储返回数据
    data_list = []
    # 根据id查询员工
    try:
        user = Users.objects.get(id=user_id)
    except Exception as e:
        data = {"success": False, "data": {"msg": "员工查询出错，请重试!"}}
        return JsonResponse(data)
    # 根据id查询任务
    for task_id in task_list:
        data_dict = {}
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "任务查询出错，请重试!"}}
            return JsonResponse(data)
        if task.stage.id == 5:
            continue
        if task.state != 1:
            continue
        # 任务分配完成 将任务的状态和阶段进行重新赋值
        task.state = 2
        task.save()
        # 调用add方法 添加多对多关系的外键数据
        user.task.add(task)
        # 创建历史数据
        history = History()
        history.book = task.code
        history.stage = task.stage
        history.start_time = datetime.now()
        history.user = user
        history.task = task
        history.save()
        # 发送系统通知
        notify.send(
            request.user,
            recipient=user,
            verb='分配了任务给你',
            target=task
        )
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["state"] = task.state
        data_dict["stage"] = task.stage.name
        data_dict["next_stage"] = task.next_stage
        name_list = []
        # 获取任务的全部人员 并进行遍历获取名字
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 查询该员工的任务
@login_required()
def get_user_task(request):
    if request.method == 'GET':
        data_list = []
        user = request.user
        tasks = user.task.all()
        for task in tasks:
            data_dict = {}
            data_dict["user"] = user.name
            data_dict["task_id"] = task.id
            data_dict["code"] = task.code.code
            data_dict["work"] = task.code.work.name
            data_dict["stage"] = task.stage.name
            data_dict["state"] = task.state
            data_list.append(data_dict)
        data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
        return JsonResponse(data)
    else:
        return HttpResponse("这个接口需要用GET方法访问！")


# 完成任务
@login_required()
@json_validate(finished_task_schema)
def finished_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    task_id = req_data["task_id"]
    user = request.user
    task_id_list = list(task.id for task in user.task.all())
    if task_id not in task_id_list:
        data = {"success": False, "data": {"msg": "所完成的任务不在此员工的任务列表中!"}}
        return JsonResponse(data)
    try:
        task = Task.objects.get(id=task_id)
    except Exception as e:
        data = {"success": False, "data": {"msg": "查询任务出错!"}}
        return JsonResponse(data)
    if task.state != 2:
        data = {"success": False, "data": {"msg": "此任务当前状态为%s，无法完成!" % task.state}}
        return JsonResponse(data)
    task.state = 3
    task.save()
    data_dict = {}
    data_dict["name"] = user.name
    data_dict["code"] = task.code.code
    data_dict["work"] = task.code.work.name
    data_dict["stage"] = task.stage.name
    data_dict["state"] = task.state
    data = {"success": True, "data": {"msg": "完成任务成功!", "data": data_dict}}
    return JsonResponse(data)


# 将任务提交到审核区
@login_required()
@json_validate(create_checking_task_schema)
def create_checking_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    task_list = req_data["task_list"]
    data_list = []
    for task_id in task_list:
        data_dict = {}
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "任务查询失败!"}}
            return JsonResponse(data)
        task.state = 4
        task.save()
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["work"] = task.code.work.name
        data_dict["stage"] = task.stage.name
        data_dict["state"] = task.state
        name_list = []
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "提交完成!", "data": data_list}}
    return JsonResponse(data)


# 查询待审核的任务
@login_required()
def get_checking_task(request):
    user = request.user
    position = user.position
    if position == 1:
        tasks = Task.objects.filter(stage=StageName.objects.get(id=position), state=4)
    elif position == 5:
        tasks = Task.objects.filter(stage_id__in=[4, 5], state=4)
    elif position == 2:
        data = {"success": True, "data": {"msg": "您无需审核!"}}
        return JsonResponse(data)
    else:
        stage_num = position-1
        stage = StageName.objects.get(id=stage_num)
        tasks = Task.objects.filter(stage=stage, state=4)
    data_list = []
    for task in tasks:
        data_dict = {}
        data_dict["task_id"] = task.id
        data_dict["code"] = task.code.code
        data_dict["work"] = task.code.work.name
        data_dict["stage"] = task.stage.name
        data_dict["state"] = task.state
        name_list = []
        users = task.userOfTask.all()
        for user in users:
            name = user.name
            name_list.append(name)
        data_dict["task_users"] = name_list
        data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完成!", "data": data_list}}
    return JsonResponse(data)


# 审核
@login_required()
@json_validate(check_task_schema)
def check_task(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    # 获取审核结果 1为通过审核 2为每通过
    check_flag = req_data["check_flag"]
    task_list = req_data["task_list"]
    for task_id in task_list:
        try:
            task = Task.objects.get(id=task_id)
        except Exception as e:
            data = {"success": False, "data": {"msg": "查询任务失败!"}}
            return JsonResponse(data)
        if check_flag == 1:
            task.stage = StageName.objects.get(id=task.next_stage)
            if task.stage.id == 5:
                task.next_stage = 6
                task.state = 3
            if task.stage.id < 4:
                task.next_stage = task.stage.id + 1
                task.state = 1
            elif task.stage.id == 4:
                task.next_stage = task.stage.id + 1
                task.state = 4
            # 将任务的完成时间添加到历史数据
            try:
                history = task.historyOfTask.filter(stage=task.stage)
                for i in history:
                    i.finish_time = datetime.now()
                    i.save()
                    # 发送系统通知
                    notify.send(
                        request.user,
                        recipient=i.user,
                        verb='通过了你的审核',
                        target=task
                    )
            except Exception as e:
                data = {"success": False, "data": {"msg": "查询历史任务出错!"}}
                return JsonResponse(data)
            task.userOfTask.clear()
            task.save()
        elif check_flag == 2:
            task.state = 2
            try:
                reason = req_data["reason"]
            except Exception as e:
                data = {"success": False, "data": {"msg": "如审核不通过，请将原因填入!"}}
                return JsonResponse(data)
            task.save()
            # 将原因作为通知发送给用户
            notify.send(
                request.user,
                recipient=task.userOfTask,
                verb='未通过您的审核',
                target=task,
                description=reason
            )
        book = task.code
        if Task.objects.filter(code=book, stage__lt=6).count() == 0:
            book.finished = True
            book.save()
            work = book.work
            if work.bookOfWork.all().filter(finished=False).count() == 0:
                work.state = 3
    data = {"success": True, "data": {"msg": "操作成功!"}}
    return JsonResponse(data)


# 查询未归还图书
@login_required()
@json_validate(get_not_back_books_schema)
def get_not_back_books(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    work_name = req_data["work_name"]
    works = Work.objects.filter(name=work_name)
    data_list = []
    for work in works:
        books = work.bookOfWork.all().filter(finished=True, return_back=False)
        for book in books:
            data_dict = {}
            data_dict["code"] = book.code
            data_dict["name"] = book.name
            data_dict["work"] = book.work.name
            data_dict["create_date"] = book.create_date
            data_list.append(data_dict)
    data = {"success": True, "data": {"msg": "查询完毕!", "data": data_list}}
    return JsonResponse(data)


# 归还图书
@login_required()
def return_back_books(request):
    json_str = request.body
    json_str = json_str.decode()
    req_data = json.loads(json_str)
    book_list = req_data["book_list"]
    data_list = []
    for book_id in book_list:
        data_dict = {}
        try:
            book = Books.objects.get(id=book_id)
            book.return_back = True
            book.save()
            data_dict['name'] = book.name
            data_list.append(data_dict)
        except Exception as e:
            return HttpResponse("%s归还图书失败，请重试！" % book_id)
    data = {"success": True, "data": {"msg": "归还图书成功!", "data":data_list}}
    return JsonResponse(data)



